Creating Reusable JavaBean Classes
Course: Advanced Java Training
Topic: Creating Reusable JavaBean Classes
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to JavaBean Classes
A JavaBean is a reusable Java software component that follows established conventions for exposing properties, methods, and, where needed, events and persistent state. JavaBeans are useful for organizing application data into reusable objects that can be accessed by different parts of a Java application.
In Advanced Java web development, JavaBean classes are often used to represent form data, user details, product information, student records, and other application objects. A JSP page can access a bean's properties using Expression Language (EL), while servlets can create and populate bean objects before forwarding requests to JSP pages.
For example, instead of passing a student's name, email address, and course name through many separate variables, a developer can create one reusable StudentBean object containing those properties.
Example of a JavaBean
public class StudentBean {
private String name;
private String email;
public StudentBean() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
This class encapsulates student information using private fields and public getter and setter methods. Its public no-argument constructor supports common JavaBean conventions and tools that instantiate beans reflectively.
2. Learning Objectives
- Understand JavaBeans and their role in Java applications.
- Identify the conventions used to create reusable JavaBean classes.
- Understand encapsulation, properties, getters, and setters.
- Create JavaBeans for students, employees, products, and other entities.
- Use JavaBeans in servlets and JSP pages.
- Understand how JSP Expression Language accesses bean properties.
- Learn how to use beans for transferring data between application layers.
- Understand basic validation, serialization, and security considerations.
- Apply best practices for designing maintainable reusable classes.
3. What Makes a Java Class a JavaBean?
JavaBeans are based on conventions rather than a requirement to extend a special base class. A JavaBean does not have to inherit from a particular superclass or implement a mandatory JavaBean interface.
For conventional JavaBeans used in JSP applications, developers commonly follow these guidelines:
- Declare the class as public when it needs to be accessed from other packages.
- Provide a public no-argument constructor when the framework or tool expects to instantiate the bean using that constructor.
- Keep properties private to support encapsulation.
- Expose properties through public getter and setter methods following JavaBean naming conventions.
- Use appropriate data types for properties.
- Implement
Serializable when object serialization is required by the application's use case.
- Keep methods focused and provide clear names.
Important: Implementing Serializable is not a universal requirement for every JavaBean. Add it when the bean needs to support serialization or a framework specifically requires it.
4. Understanding Encapsulation in JavaBeans
Encapsulation is an object-oriented programming principle in which data and the methods that operate on it are grouped together. A class controls access to its internal state by using access modifiers and public methods.
In a JavaBean, properties are usually stored in private fields. Other classes interact with these fields through getter and setter methods instead of accessing them directly.
Example
public class EmployeeBean {
private String employeeName;
private double salary;
public EmployeeBean() {
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if (salary < 0) {
throw new IllegalArgumentException(
"Salary cannot be negative"
);
}
this.salary = salary;
}
}
In this example, the fields are private, and the setter for salary applies a basic validation rule. This helps prevent invalid values from being assigned through the public property interface.
5. JavaBean Properties
A JavaBean property is an attribute exposed through accessor methods. The property name is inferred from the method names by JavaBean naming conventions.
| Property Type |
Method Pattern |
Example |
| Read-write property |
getX() and setX(value) |
getName(), setName(String name) |
| Read-only property |
getX() without a setter |
getRegistrationId() |
| Write-only property |
setX(value) without a getter |
setPasswordInput(String value) |
| Boolean property |
isX() or getX() |
isActive() |
For a Boolean property such as active, the method isActive() is a common convention. A setter may be named setActive(boolean active).
6. Getter and Setter Methods
Getter and setter methods provide controlled access to properties. They also allow a class to validate values, calculate derived properties, or enforce rules before updating its internal state.
Getter Method
A getter returns the current value of a property.
public String getName() {
return name;
}
Setter Method
A setter assigns a value to a property.
public void setName(String name) {
this.name = name;
}
The keyword this refers to the current object. In the example, this.name represents the instance field, while name represents the method parameter.
Why Use Getters and Setters?
- They help maintain encapsulation.
- They provide a consistent property-access pattern.
- They allow validation before values are stored.
- They support tools and frameworks that inspect JavaBean properties.
- They allow implementation details to change without requiring callers to access fields directly.
7. Step-by-Step: Creating a Reusable StudentBean Class
In this example, a JavaBean stores basic student information and can be reused in servlets, JSP pages, and ordinary Java classes.
Step 1: Create the Package
Create a package named com.example.beans for reusable data classes.
src/main/java/
com/
example/
beans/
StudentBean.java
Step 2: Define the Properties
The student bean will contain an ID, name, email address, and course name.
Step 3: Implement the JavaBean
package com.example.beans;
public class StudentBean {
private int studentId;
private String name;
private String email;
private String courseName;
public StudentBean() {
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
Step 4: Create and Populate the Bean
A servlet or another Java class can create an instance and assign values through its setters.
import com.example.beans.StudentBean;
public class StudentBeanDemo {
public static void main(String[] args) {
StudentBean student = new StudentBean();
student.setStudentId(101);
student.setName("Aarav Sharma");
student.setEmail("[email protected]");
student.setCourseName("Advanced Java");
System.out.println(student.getStudentId());
System.out.println(student.getName());
System.out.println(student.getEmail());
System.out.println(student.getCourseName());
}
}
Step 5: Verify the Output
101
Aarav Sharma
[email protected]
Advanced Java
The same StudentBean class can now be reused by multiple application components without repeating the property definitions.
8. Using JavaBeans in JSP Pages
JSP provides standard actions for working with JavaBeans. The <jsp:useBean> action locates an existing bean in the specified scope or creates one if needed. The <jsp:setProperty> action sets a property, while <jsp:getProperty> retrieves and displays a property.
8.1 Using jsp:useBean
<jsp:useBean
id="student"
class="com.example.beans.StudentBean"
scope="request" />
Here, student is the JSP variable name, class specifies the JavaBean class, and scope="request" indicates request scope.
8.2 Setting a Property
<jsp:setProperty
name="student"
property="name"
value="Aarav Sharma" />
<jsp:setProperty
name="student"
property="courseName"
value="Advanced Java" />
The name attribute identifies the bean, and the property attribute identifies the property to set. The property must have a compatible setter.
8.3 Getting a Property
<p>Student Name:
<jsp:getProperty name="student" property="name" />
</p>
<p>Course:
<jsp:getProperty name="student" property="courseName" />
</p>
Security note: Do not assume that <jsp:getProperty> automatically HTML-escapes every value. For output that may contain untrusted text, prefer context-appropriate escaping, such as JSTL <c:out>.
9. Using JavaBeans with JSP Expression Language
Expression Language (EL) provides a concise way to access properties of objects available in JSP scopes. If a bean is available under the name student, EL can access its properties using expressions such as ${student.name}.
Example JSP
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Student Details</h2>
<p>ID: ${student.studentId}</p>
<p>Name: <c:out value="${student.name}" /></p>
<p>Email: <c:out value="${student.email}" /></p>
<p>Course: <c:out value="${student.courseName}" /></p>
</body>
</html>
In modern Jakarta Tags environments, the core JSTL tag library URI is commonly jakarta.tags.core. Older applications may use a legacy JSTL URI depending on the library version. Use the URI and dependencies supported by the application.
EL resolves bean properties through the corresponding accessor methods. For example, ${student.name} normally calls the bean's getName() method.
10. Passing Form Data into a JavaBean
JavaBeans are useful for collecting form data into a structured object. A servlet can read submitted form fields, populate a bean, validate the values, and then forward the bean to a JSP page.
Example HTML Form
<form action="student-register" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="courseName">Course:</label>
<input type="text" id="courseName" name="courseName" required>
<button type="submit">Register</button>
</form>
Example Jakarta Servlet
package com.example.web;
import com.example.beans.StudentBean;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/student-register")
public class StudentRegisterServlet extends HttpServlet {
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String email = request.getParameter("email");
String courseName = request.getParameter("courseName");
if (name == null || name.isBlank()
|| email == null || email.isBlank()
|| courseName == null || courseName.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Required fields are missing."
);
return;
}
StudentBean student = new StudentBean();
student.setName(name.trim());
student.setEmail(email.trim());
student.setCourseName(courseName.trim());
request.setAttribute("student", student);
request.getRequestDispatcher("/student-details.jsp")
.forward(request, response);
}
}
This example shows the basic flow from an HTML form to a servlet, then into a JavaBean, and finally to a JSP page. Production applications should also validate email syntax, enforce business rules, apply request-size limits where appropriate, and handle validation errors consistently. Client-side form validation alone is not sufficient.
11. Understanding JavaBean Scopes in JSP
When a bean is created or located through JSP actions, its scope determines how long it is available and which components can access it.
| Scope |
Availability |
Common Use |
page |
Only within the current JSP page |
Temporary values used by one page |
request |
Throughout the current request, including a forward |
Passing form results from a servlet to a JSP |
session |
Across multiple requests in the same HTTP session |
User-specific state that needs to persist between requests |
application |
Across requests within the web application |
Shared application-wide data where appropriate |
Example of creating a bean in request scope:
<jsp:useBean
id="student"
class="com.example.beans.StudentBean"
scope="request" />
Choose the narrowest scope that satisfies the requirement. Do not store sensitive or user-specific data in application scope, and be careful when placing mutable objects in session or application scope because they may be shared across concurrent requests.
12. Reusing JavaBeans Across Application Layers
A key benefit of reusable JavaBean classes is that several parts of an application can work with the same data structure.
- Servlets: Create and populate beans using request parameters or service results.
- JSP pages: Read bean properties using EL or JSP standard actions.
- Service classes: Accept and return structured data objects.
- Data access code: Map database results into suitable Java objects.
- Tests: Create beans with known values to test application behavior.
For example, a course registration application can use a StudentBean to transfer student details between a registration servlet and a confirmation page. In larger applications, developers may introduce separate domain objects, request DTOs, and response DTOs to avoid mixing concerns.
13. JavaBean vs. Ordinary Java Class
| Feature |
JavaBean |
Ordinary Java Class |
| Design conventions |
Usually follows standard property and constructor conventions |
Can follow any suitable design |
| Properties |
Often exposed through getters and setters |
May expose fields or methods in different ways |
| Constructor |
Commonly provides a public no-argument constructor for tool compatibility |
May provide only parameterized constructors |
| Reusability |
Designed to expose consistent reusable component properties |
Can also be reusable, depending on its design |
| Serialization |
Can support serialization when needed |
Can also support serialization when implemented appropriately |
| Inheritance |
No special superclass is required |
Inheritance depends on application design |
A JavaBean is still a Java class. The distinction is primarily about conventions and the way its properties and other component features are exposed.
14. JavaBean vs. Enterprise JavaBeans (EJB)
JavaBeans and Enterprise JavaBeans have similar names but serve different purposes.
| Feature |
JavaBean |
Enterprise JavaBeans (EJB) |
| Main purpose |
Reusable component or data object |
Enterprise business component managed by an EJB container |
| Typical implementation |
Plain Java class following JavaBean conventions |
Enterprise component using supported EJB APIs and rules |
| Container requirement |
Does not inherently require a specialized enterprise container |
Runs within an EJB-compatible runtime |
| Common usage |
Form data, view data, reusable properties |
Enterprise services and business operations |
| Example |
StudentBean |
An EJB service for processing business operations |
15. JavaBean Serialization
Serialization converts an object's state into a representation that can be stored or transmitted and later reconstructed. A Java class can support standard Java object serialization by implementing java.io.Serializable, provided its serialized object graph meets the requirements.
Example Serializable JavaBean
package com.example.beans;
import java.io.Serializable;
public class ProductBean implements Serializable {
private static final long serialVersionUID = 1L;
private int productId;
private String productName;
private double price;
public ProductBean() {
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 0) {
throw new IllegalArgumentException(
"Price cannot be negative"
);
}
this.price = price;
}
}
The serialVersionUID field helps identify the version of a serializable class. Actual compatibility depends on the class structure and serialization rules.
Security note: Do not deserialize untrusted serialized data. Java native deserialization can introduce serious security risks when used with untrusted input. Use serialization only when the application has a clear need and appropriate safeguards.
16. JavaBean Validation and Data Integrity
Reusable beans should help maintain clear data contracts. Simple validation can be performed in setters, but complex validation often belongs in a dedicated validation layer or service.
Example with Basic Validation
public class AccountBean {
private String username;
private int age;
public AccountBean() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
if (username == null || username.isBlank()) {
throw new IllegalArgumentException(
"Username is required"
);
}
this.username = username.trim();
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0 || age > 130) {
throw new IllegalArgumentException(
"Age is outside the permitted range"
);
}
this.age = age;
}
}
Validation rules should be appropriate to the data. For example, checking that an email is non-empty does not prove that it is valid or that the user controls the address. Keep validation consistent across entry points and do not rely only on values submitted by a browser.
17. Common Errors When Creating JavaBeans
| Error |
Reason |
Solution |
| JSP cannot instantiate the bean |
The class is missing, inaccessible, or lacks a constructor expected by the creation mechanism |
Check the package, deployment, accessibility, and constructor. |
| Property is not found |
Getter or setter naming does not match JavaBean conventions |
Verify method names and property spelling. |
| Property value is not updated |
The setter was not called or the wrong bean instance is being used |
Check scope, bean identity, and property assignment. |
| EL returns an unexpected value |
The bean is unavailable in the expected scope or the property name is wrong |
Check the attribute name, scope, and getter method. |
| Type conversion fails |
A submitted value cannot be converted to the target property type |
Validate input and handle conversion errors explicitly. |
| Invalid values are stored |
There is no validation or the validation is incomplete |
Introduce appropriate validation in the application layer. |
| Unexpected serialization error |
A field in the serialized object graph is not serializable |
Review the object graph and serialization requirements. |
| Bean state is shared unexpectedly |
A mutable bean is stored in a broader scope than intended |
Use the narrowest suitable scope and manage concurrent access. |
18. Best Practices for Creating Reusable JavaBeans
- Use meaningful class and property names.
- Keep fields private and expose properties through appropriate accessors.
- Provide a public no-argument constructor when required by the intended framework or tooling.
- Choose property types that reflect the data being represented.
- Apply appropriate validation and define how invalid values are handled.
- Keep a data bean focused on its intended responsibility.
- Avoid placing database queries, servlet request handling, or JSP rendering code inside a basic data bean.
- Implement
Serializable only when there is a concrete need or a framework requirement.
- Be careful when storing mutable beans in session or application scope.
- Escape untrusted values when rendering them in JSP pages.
- Use tests to verify getters, setters, validation rules, and boundary cases.
- Keep JavaBean property names consistent with the JSP EL expressions that access them.
19. Practical Exercise
Task: Create a reusable EmployeeBean class for an employee management application.
Requirements
- Create a class named
EmployeeBean in a suitable package.
- Declare private properties for employee ID, name, department, and salary.
- Provide a public no-argument constructor.
- Create getter and setter methods for the properties.
- Validate that the employee name and department are not blank.
- Reject a negative salary.
- Create an instance in a Java demo class and display the property values.
- Use the bean in a servlet and display its properties on a JSP page.
Expected Learning Outcome
After completing this exercise, you should be able to design a reusable JavaBean, populate it with data, access its properties through standard methods, and transfer it between a servlet and a JSP page.
20. Mini Project: Student Registration System
Build a simple student registration application that uses JavaBeans to organize student information and transfer data between application layers.
Project Features
- A student registration form with name, email, and course fields.
- A reusable
StudentBean data class.
- A servlet that reads and validates form input.
- Request attributes used to pass the bean to a JSP page.
- A JSP confirmation page that accesses bean properties using EL.
- Appropriate output escaping for displayed user data.
- Clear handling of missing or invalid fields.
- Optional database integration through a separate service or data-access layer.
Suggested Project Structure
src/main/java/
com/example/beans/
StudentBean.java
com/example/web/
StudentRegisterServlet.java
src/main/webapp/
student-form.jsp
student-details.jsp
WEB-INF/
web.xml
The application can use servlet annotations instead of declaring the servlet in web.xml, depending on the project's configuration.
21. Interview Questions and Answers
Q1. What is a JavaBean?
Answer: A JavaBean is a reusable Java component that follows conventions for exposing properties, methods, and optionally events and persistent state.
Q2. Why are JavaBeans used in Advanced Java applications?
Answer: They organize data into reusable objects and make it easier to pass structured information between servlets, JSP pages, service classes, and other application components.
Q3. Is inheritance from a special base class required for JavaBeans?
Answer: No. JavaBeans do not have to extend a specific base class or implement a mandatory JavaBean interface.
Q4. What is the purpose of a no-argument constructor?
Answer: It allows common frameworks and tools to instantiate the bean without needing constructor arguments. It is a widely used JavaBean convention, especially when JSP or reflection-based mechanisms create instances.
Q5. What is a JavaBean property?
Answer: A property is an attribute exposed through accessor methods, typically following getter and setter naming conventions.
Q6. What is the difference between a getter and a setter?
Answer: A getter returns a property's value, while a setter assigns or updates the value.
Q7. What is the role of encapsulation in JavaBeans?
Answer: Encapsulation keeps internal fields private and provides controlled access through methods, allowing validation and other rules to be applied.
Q8. How can a JSP page access JavaBean properties?
Answer: It can use JSP standard actions such as <jsp:getProperty> or Expression Language, such as ${student.name}, when the bean is available in a JSP scope.
Q9. What is the purpose of jsp:useBean?
Answer: It locates a bean in a specified scope or creates one if needed, depending on the action's attributes and the current scope state.
Q10. What is the difference between request scope and session scope?
Answer: Request scope makes an attribute available during the current request, including a forward. Session scope allows data to remain available across multiple requests within the same HTTP session.
Q11. Must every JavaBean implement Serializable?
Answer: No. Implement it when serialization is required by the use case or by a framework's expectations.
Q12. What is the difference between JavaBeans and Enterprise JavaBeans?
Answer: JavaBeans are reusable Java components that commonly encapsulate properties. Enterprise JavaBeans are enterprise components designed to run in an EJB-compatible container and support enterprise application services.
Q13. How can a servlet use a JavaBean?
Answer: A servlet can instantiate the bean, populate its properties, place it in a request or another suitable scope, and forward the request to a JSP page.
Q14. Why should output from a JavaBean be escaped in a JSP?
Answer: Bean properties may contain untrusted text. Appropriate context-aware output encoding helps prevent cross-site scripting and unintended markup interpretation.
Q15. What are common JavaBean design mistakes?
Answer: Common mistakes include incorrect accessor naming, missing constructors where required, weak validation, inappropriate scope selection, unsafe output rendering, and mixing presentation or database logic into data classes.
22. Quick Revision Checklist
- Understand the meaning and purpose of JavaBeans.
- Know the common constructor and property conventions.
- Understand private fields, getters, and setters.
- Know how to create and populate a reusable bean.
- Understand how servlets can pass beans to JSP pages.
- Know how JSP standard actions and EL access bean properties.
- Understand page, request, session, and application scopes.
- Distinguish JavaBeans from Enterprise JavaBeans.
- Know when serialization is appropriate.
- Validate input and encode output safely.
- Keep reusable data classes focused and maintainable.
23. Conclusion
Creating reusable JavaBean classes is a foundational skill in Advanced Java development. JavaBeans provide a consistent way to represent structured data and expose properties through standard methods. They are particularly useful in JSP and servlet applications, where data needs to move between forms, controllers, and presentation pages.
By following JavaBean conventions, applying appropriate validation, selecting the correct scope, and keeping presentation and business responsibilities separate, developers can create reusable classes that are easier to maintain, test, and extend.
24. Learning Resources and Course Links